//
//  HRCircleOfFirendsViewController.m
//  Hear
//
//  Created by mac on 2017/10/31.
//  Copyright © 2017年 mac. All rights reserved.
//  

#import "HRCircleOfFirendsViewController.h"
#import "XXPageTabView.h"
#import "XXPageTabItemLable.h"
#import "HRDynamicMessageViewController.h"
#import "HRFollowDynamicViewController.h"
#import "HRSegmentView.h"
#import "PopMenu.h"
#import "HRPostDynamicViewController.h"
#import "HRRecordAudioViewController.h"
#import "HRFMDBDynamicNotifacationTool.h"
#import "HRCicleAnswerListViewController.h"
#import "HRDynamicViewController.h"

#import "HRAudioPlayerView.h"
#import "HRSquareAudioPlayerViewModel.h"
#import "HRSquareAudioPlayerModel.h"
#import "UIImageView+EMWebCache.h"
#import "DOUAudioStreamer.h"
#import "DOUAudioVisualizer.h"
#import "HRDouAudioStreamerModel.h"
#import "Track.h"

#define INITVOLUME 0.6

static void *kStatusKVOKey = &kStatusKVOKey;
static void *kDurationKVOKey = &kDurationKVOKey;
static void *kBufferingRatioKVOKey = &kBufferingRatioKVOKey;
static int num = 0;
@interface HRCircleOfFirendsViewController ()<XXPageTabViewDelegate>
@property (nonatomic, strong) XXPageTabView *pageTabView;
@property(nonatomic, strong)HRFollowDynamicViewController *dynaVC;
@property(nonatomic, strong)HRDynamicMessageViewController *dynaMessageVC;
@property (nonatomic, strong)HRSegmentView *segmentView;
@property (nonatomic, strong) PopMenu *popMenu;
@property(nonatomic, strong)UILabel *circleLabel;
@property(nonatomic, strong)UIButton *postButton;

@property(nonatomic, strong)HRCicleAnswerListViewController *answerListVC;
@property(nonatomic, strong)HRSquareAudioPlayerViewModel *squareAudioPlayerVM;
@property(nonatomic, strong)HRAudioPlayerView *audioPalyerView;
@property(nonatomic, strong)NSMutableArray *mutableSongURLArr;
@property(nonatomic, strong)NSMutableArray *mutableHeadImageArr;
@property (nonatomic, strong) DOUAudioStreamer *streamer;
@property (nonatomic, strong) Track *track;//audioTrack
@property (nonatomic, strong) NSMutableArray *modelMutableArr;
@property (nonatomic, strong) HRDynamicViewController *dynamicVC;
@property(nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) BOOL sliding;
@property(nonatomic, strong) HRSquareAudioPlayerModel *hrSquareAudioPlayerModel;
@property(nonatomic, strong) AVPlayer *player;
@property(nonatomic, assign) BOOL isPlaying;
@property(nonatomic, strong) AVAudioPlayer *audioPlayer;


@end

@implementation HRCircleOfFirendsViewController

-(HRSquareAudioPlayerModel *) hrSquareAudioPlayerModel
{
    if (!_hrSquareAudioPlayerModel) {
        _hrSquareAudioPlayerModel = [HRSquareAudioPlayerModel new];
    }
    return _hrSquareAudioPlayerModel;
}


-(HRAudioPlayerView *)audioPalyerView
{
    if (!_audioPalyerView) {
        _audioPalyerView = [HRAudioPlayerView new];
        _audioPalyerView.frame = CGRectMake(0, 64, kFullWidth, 59);
//        [_audioPalyerView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo(self.view.mas_top).offset(64);
//            make.left.equalTo(self.view.mas_left).offset(0);
//            make.width.mas_equalTo(kFullWidth);
//            make.height.mas_equalTo(54);
//        }];
        [self.view addSubview:_audioPalyerView];
    }
    return _audioPalyerView;
}

-(HRSquareAudioPlayerViewModel *)squareAudioPlayerVM
{
    if (!_squareAudioPlayerVM) {
        _squareAudioPlayerVM = [HRSquareAudioPlayerViewModel new];
    }
    return _squareAudioPlayerVM;
}

-(NSMutableArray *)mutableSongURLArr
{
    if (!_mutableSongURLArr) {
        _mutableSongURLArr = [[NSMutableArray alloc] initWithCapacity:1];
    }
    return _mutableSongURLArr;
}

-(NSMutableArray *)modelMutableArr
{
    if (!_modelMutableArr) {
        _modelMutableArr = [[NSMutableArray alloc] initWithCapacity:1];
        
    }
    return _modelMutableArr;
}

-(NSMutableArray *)mutableHeadImageArr
{
    if (!_mutableHeadImageArr) {
        _mutableHeadImageArr = [[NSMutableArray alloc] initWithCapacity:1];
    }
    return _mutableHeadImageArr;
}

-(XXPageTabView *)pageTabView{
    if (!_pageTabView){
        _pageTabView = [[XXPageTabView alloc] initWithChildControllers:self.childViewControllers childTitles:@[@"点滴",@"留声机"]];
        _pageTabView.frame = self.view.bounds;
        _pageTabView.height -= 49;
        _pageTabView.delegate = self;
        _pageTabView.titleStyle = XXPageTabTitleStyleGradient;
        _pageTabView.indicatorStyle = XXPageTabIndicatorStyleStretch;
        _pageTabView.tabItemFont = CustomUIFont(17);
        _pageTabView.indicatorWidth = 64;
        _pageTabView.unSelectedColor = FirstTextColor;
        _pageTabView.selectedColor = CustomColor(255, 255, 255, 1);
        _pageTabView.tabSize = CGSizeMake(64*2, kStatusBarHeight+kNavBarHeight);
        _pageTabView.tabBackgroundColor = NavTinColor;
        _pageTabView.backgroundColor = NavTinColor;
        _pageTabView.bodyBounces = NO;
        _pageTabView.minScale = 0.85;
        _pageTabView.bodyView.scrollEnabled = NO;
        _pageTabView.selectedTabIndex = self.selectedTabIndex;

//        UILabel *circleLabel = [[UILabel alloc] initWithFrame:CGRectMake(kFullWidth/2+80, kStatusBarHeight, 10, 10)];
//        circleLabel.hidden = !([[HRFMDBDynamicNotifacationTool sharedInstance] unReadCount:@[@"1"]] || [[HRFMDBDynamicNotifacationTool sharedInstance] unReadCount:@[@"5"]] ||[[HRFMDBDynamicNotifacationTool sharedInstance] unReadCount:@[@"2"]]);
//        circleLabel.layer.cornerRadius = 5;
//        circleLabel.clipsToBounds = YES;
//        circleLabel.backgroundColor = CustomColor(250, 26, 41, 1);
//        [_pageTabView  addSubview:(self.circleLabel=circleLabel)];
    }
    return _pageTabView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newMessageNotifi) name:@"newMesageNotifi" object:nil];
    
     [self getAudioPlayerData];
}

- (void)newMessageNotifi{
    self.circleLabel.hidden = !([[HRFMDBDynamicNotifacationTool sharedInstance] unReadCount:@[@"1"]] || [[HRFMDBDynamicNotifacationTool sharedInstance] unReadCount:@[@"5"]] ||[[HRFMDBDynamicNotifacationTool sharedInstance] unReadCount:@[@"2"]]);
}

- (void)setupView{
    
    HRFollowDynamicViewController *dynaVC = [HRFollowDynamicViewController new];
    dynaVC.dynamicType = FollowDynaimc;
    dynaVC.view.frame = CGRectMake(0, kNavBarHeight, kFullWidth, kFullHeight-kNavBarHeight);
//    dynaVC.view.frame = CGRectMake(0, kNavBarHeight + 128, kFullWidth, kFullHeight-kNavBarHeight - 128);
    self.dynaVC = dynaVC;
    
    
    HRCicleAnswerListViewController *answerListVC = [HRCicleAnswerListViewController new];
    answerListVC.view.frame = CGRectMake(kFullWidth, kNavBarHeight, kFullWidth, kFullHeight-kNavBarHeight);
//    answerListVC.view.frame = CGRectMake(kFullWidth, kNavBarHeight + 128, kFullWidth, kFullHeight-kNavBarHeight-128);
    self.answerListVC=answerListVC;

//    HRDynamicMessageViewController *dynaMessageVC = [HRDynamicMessageViewController new];
//    dynaMessageVC.view.frame = CGRectMake(kFullWidth*2, kNavBarHeight, kFullWidth, kFullHeight-kNavBarHeight);
//    self.dynaMessageVC = dynaMessageVC;
    
    [self addChildViewController:dynaVC];
    [self addChildViewController:answerListVC];
//    [self addChildViewController:dynaMessageVC];
    [self.view addSubview:self.pageTabView];

    
//    self.playButton = [UIButton buttonWithType:0];
//    [self.playButton setImage:[UIImage imageNamed:@"动画0"] forState:0];
//    [self.playButton addTarget:self action:@selector(targetPlayButton) forControlEvents:UIControlEventTouchUpInside];
//    [self.bottomView addSubview:self.playButton];
//    NSArray *animateNames = @[@"动画0",@"动画1",@"动画2"];
//    NSMutableArray * animationImages = [[NSMutableArray alloc] initWithCapacity:animateNames.count];
//    for (NSString * animateName in animateNames) {
//        UIImage * animateImage = [UIImage imageNamed:animateName];
//        [animationImages addObject:animateImage];
//    }
//    self.playButton.imageView.animationImages = animationImages;
//    self.playButton.imageView.animationDuration = 0.7;
    
    UIButton *backButton = [UIButton buttonWithType:0];
    [backButton setImage:[UIImage imageNamed:@"1"] forState:0];
    [backButton setTarget:self action:@selector(openPlayerView) forControlEvents:UIControlEventTouchUpInside];
    NSMutableArray *imgArray = [NSMutableArray arrayWithCapacity:1];
    for (int i = 1; i < 4; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d",i]];
        [imgArray addObject:image];
    }
    backButton.imageView.animationImages = imgArray;
    backButton.imageView.animationDuration = 0.7;
    //    rightButton.size = CGSizeMake(40, 40);

//    [backButton addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    backButton.frame = CGRectMake(0, kStatusBarHeight, 40, 40);
    [self.pageTabView addSubview:backButton];
    
    UIButton *postButton = [UIButton buttonWithType:0];
    [postButton setImage:[UIImage imageNamed:@"发帖按钮"] forState:0];
    //    rightButton.size = CGSizeMake(40, 40);
    postButton.titleLabel.font = CustomUIFont(13);
    [postButton addTarget:self action:@selector(postClick) forControlEvents:UIControlEventTouchUpInside];
    postButton.frame = CGRectMake(kFullWidth-60, kStatusBarHeight, 60, 40);
    [self.pageTabView addSubview:postButton];
    self.postButton = postButton;
    
    if (self.selectedTabIndex ==2){
        [self.postButton setImage:nil forState:0];
        [self.postButton setTitle:@"一键清空" forState:0];
    }
    
    //     打开播放界面
//    [self openPlayerView];
    
}
#pragma mark  -----   打开播放器界面
-(void)openPlayerView
{
    [self audioPalyerView];
    _audioPalyerView.hidden = NO;
    //    [_audioPalyerView.playBtn addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_audioPalyerView.playBtn addTarget:self action:@selector(myBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    //    [_audioPalyerView.nextBtn addTarget:self action:@selector(nextButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [_audioPalyerView.nextBtn addTarget:self action:@selector(nextBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//    [_audioPalyerView.slider addTarget:self action:@selector(volumeslidervaluechange:) forControlEvents:UIControlEventValueChanged];
    [_audioPalyerView.slider addTarget:self action:@selector(_actionSliderProgress:) forControlEvents:UIControlEventValueChanged];
    //    [_audioPalyerView.slider addTarget:self action:@selector(durationSliderTouchEnded:) forControlEvents:UIControlEventTouchUpInside];
    [_audioPalyerView.userHeadBtn addTarget:self action:@selector(enterCurrentUser) forControlEvents:UIControlEventTouchUpInside];
    [self modelMutableArr];
    [self hrSquareAudioPlayerModel];
    
    self.isPlaying = NO;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.02
                                                  target:self
                                                selector:@selector(updateProgress)
                                                userInfo:nil
                                                 repeats:YES];
}

- (void)postClick{

    if (self.pageTabView.selectedTabIndex == 0){
        [self showMenu];
    }else if (self.pageTabView.selectedTabIndex == 1){
        
    }else{
        for (HRDynamicNotificationModel *model in self.dynaMessageVC.contentArray) {
            [[HRFMDBDynamicNotifacationTool sharedInstance] deleteRequestId:model.ID];
        }
        [self.dynaMessageVC.contentArray removeAllObjects];
        [self.dynaMessageVC.tableView reloadData];
        self.circleLabel.hidden = YES;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTabItemBageCountNotifi" object:nil];
    }
}

- (void)showMenu{
    NSMutableArray *items = [[NSMutableArray alloc] initWithCapacity:3];
    
    MenuItem *menuItem = [MenuItem itemWithTitle:@"图文动态" iconName:@"广场悬浮_心情_触摸_I"];
    [items addObject:menuItem];
    
    menuItem = [MenuItem itemWithTitle:@"语音动态" iconName:@"广场悬浮_语音_触摸_I"];
    [items addObject:menuItem];
    
    //    menuItem = [MenuItem itemWithTitle:@"视频动态" iconName:@"广场悬浮_语音_触摸_I"];
    //    [items addObject:menuItem];
    
    if (!_popMenu) {
        _popMenu = [[PopMenu alloc] initWithFrame:self.view.bounds items:items];
        _popMenu.menuAnimationType = kPopMenuAnimationTypeNetEase;
        _popMenu.perRowItemCount = 2;
    }
    if (_popMenu.isShowed) {
        return;
    }
    WeakSelf
    _popMenu.didSelectedItemCompletion = ^(MenuItem *selectedItem) {
        if ([selectedItem.title isEqualToString:@"图文动态"]){
            HRPostDynamicViewController *postDynamicVC = [HRPostDynamicViewController new];
            [weakSelf.navigationController pushViewController:postDynamicVC animated:YES];
        }else if ([selectedItem.title isEqualToString:@"语音动态"]){
            HRRecordAudioViewController *audioVC = [HRRecordAudioViewController new];
            audioVC.title = @"瞬间";
            [weakSelf.navigationController pushViewController:audioVC animated:YES];
        }else if ([selectedItem.title isEqualToString:@"视频动态"]){
        }
    };
    
    [_popMenu showMenuAtView:WINDOW];
}

- (void)backClick{
    [self.navigationController popViewControllerAnimated:YES];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

-(void)viewWillDisappear:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)pageTabViewDidEndChange {
    if (self.pageTabView.selectedTabIndex == 0){
        [self.postButton setImage:[UIImage imageNamed:@"发帖按钮"] forState:0];
        [self.postButton setTitle:@"" forState:0];
    }else if(self.pageTabView.selectedTabIndex == 1){
        [self.postButton setImage:nil forState:0];
        [self.postButton setTitle:@"" forState:0];
    }else{
        [self.postButton setImage:nil forState:0];
        [self.postButton setTitle:@"一键清空" forState:0];
    }
    DDLog(@"#####%ld", (long)self.pageTabView.selectedTabIndex);
}

#pragma mark ------ audioPlayer请求数据
-(void)getAudioPlayerData
{
    _track = [[Track alloc] init];
    
    NSMutableDictionary *audioPlayerDic = [[NSMutableDictionary alloc] initWithCapacity:0];
    [audioPlayerDic setObject:@"50000" forKey:@"PageSize"];
    [audioPlayerDic setObject:@"0" forKey:@"PageIndex"];
    [audioPlayerDic setObject:USERID forKey:@"CurrentUserLocalId"];
    NSString *url = @"SoundInfo/Get_GetSoundRecommend"; 
    [self.squareAudioPlayerVM getSqureAudioPlayerData:audioPlayerDic andUrl:url resultArray:^(NSMutableArray *resultArray) {
        NSLog(@"-----------resultArray = %@", resultArray);
        _modelMutableArr = resultArray;
        for (HRSquareAudioPlayerModel *model in resultArray) {
            [self.mutableHeadImageArr addObject:model.UserPictureName];
            [self.mutableSongURLArr addObject:model.SoundUrl];
            
        }
//         [self createPlayer];
        [self configSonginfo];
    }];
}

#pragma mark - set进度条
-(void)updateProgress{
    //专辑图片旋转
    
    CMTime currentTime = [self.player currentTime];
    Float64 currentPlaybackTime = CMTimeGetSeconds(currentTime);
    CMTime audioDuration = self.player.currentItem.duration;
    Float64 durationTime = CMTimeGetSeconds(audioDuration);
//    循环播放
//    if (currentPlaybackTime == durationTime) {
//        [self nextBtnClick:nil];
//    }
    
//    if ((int)currentPlaybackTime == (int)durationTime) {
//        [self nextBtnClick:nil];
//    }

    int currentTimeMinutes = (unsigned)currentPlaybackTime/60;
    int currentTimeSeconds = (unsigned)currentPlaybackTime%60;
    
    NSMutableString *currentTimeString;
    if (currentTimeSeconds < 10) {
        currentTimeString = [NSMutableString stringWithFormat:@"%d:0%d",currentTimeMinutes,currentTimeSeconds];
    }
    else{
        currentTimeString = [NSMutableString stringWithFormat:@"%d:%d",currentTimeMinutes,currentTimeSeconds];
    }
    
//    _audioPalyerView.progress.progress = currentPlaybackTime/[_hrSquareAudioPlayerModel.SoundLength intValue];
//    _audioPalyerView.progress.progress = currentPlaybackTime/durationTime;
    float total = CMTimeGetSeconds(self.player.currentItem.duration);
    _audioPalyerView.slider.value = currentPlaybackTime / total;

}
#pragma mark - 交互
- (void)volumeslidervaluechange:(UISlider *)sender {
    _player.volume = sender.value;
}

- (void)myBtnAction:(UIButton *)sender {
    if (self.isPlaying) {
        [self pauseSong];
    } else {
        [self playSong];
    }
}

- (void)nextBtnClick:(UIButton *)sender {
    ++num;
    if (num >= _mutableSongURLArr.count) {
        num = 0;
    }
    DDLog(@"nextBtnClick num =========%d",num);
    [[NSUserDefaults standardUserDefaults] setInteger:num forKey:@"num"];
    [self.timer setFireDate:[NSDate distantFuture]];
    [self configSonginfo];
    [self playSong];
}


#pragma mark --- 配置播放器信息
-(void)configSonginfo
{
    if (num >= _modelMutableArr.count) return;
    
    _hrSquareAudioPlayerModel = _modelMutableArr[num];
    NSURL *url = [NSURL URLWithString:_hrSquareAudioPlayerModel.SoundUrl];
    AVPlayerItem *songItem = [[AVPlayerItem alloc] initWithURL:url];
    self.player = [[AVPlayer alloc] initWithPlayerItem:songItem];
    self.player.volume = INITVOLUME ;
    [_audioPalyerView setValue:_hrSquareAudioPlayerModel];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinished) name:AVPlayerItemDidPlayToEndTimeNotification object:_player.currentItem];
}

- (void)playSong{
    [_audioPalyerView.playBtn setImage:[UIImage imageNamed:@"暂停键"] forState:UIControlStateNormal];
    [self.timer setFireDate:[NSDate date]];
    self.isPlaying = YES;
    [self.player play];
}

- (void)pauseSong {
    [_audioPalyerView.playBtn setImage:[UIImage imageNamed:@"播放键"] forState:UIControlStateNormal];
    [self.timer setFireDate:[NSDate distantFuture]];
    self.isPlaying = NO;
    [self.player pause];
}

-(void)playFinished
{
    [self nextBtnClick:nil];
}
#pragma mark ------- 用户拖动进度条，修改进度条
- (void)_actionSliderProgress:(UISlider *)sender
{
//    self.sliding = YES;
    float time = sender.value * CMTimeGetSeconds(self.player.currentItem.duration);
    [self.player seekToTime:CMTimeMake(time, 1)];
}
#pragma mark  -- audioPlayer代理以及监控


/*
 //创建streamer播放器,并配置信息
 - (void)createPlayer{
 if (num >= _modelMutableArr.count) return;
 
 _hrSquareAudioPlayerModel = _modelMutableArr[num];
 _track.audioFileURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",_hrSquareAudioPlayerModel.SoundUrl]];
 _streamer = [DOUAudioStreamer streamerWithAudioFile:_track];
 
 [_audioPalyerView setValue:_hrSquareAudioPlayerModel];
 
 
 //    _streamer = nil;
 [self addStreamerObserver];
 //    [self.streamer play];
 }
 
 - (void)addStreamerObserver {
 [_streamer addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:kStatusKVOKey];
 [_streamer addObserver:self forKeyPath:@"duration" options:NSKeyValueObservingOptionNew context:kDurationKVOKey];
 [_streamer addObserver:self forKeyPath:@"bufferingRatio" options:NSKeyValueObservingOptionNew context:kBufferingRatioKVOKey];
 }
 - (void)removeStreamerObserver {
 [_streamer removeObserver:self forKeyPath:@"status"];
 [_streamer removeObserver:self forKeyPath:@"duration"];
 [_streamer removeObserver:self forKeyPath:@"bufferingRatio"];
 }

#pragma mark -----监控
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if (context == kStatusKVOKey) {
        [self performSelector:@selector(_updateStatus)
                     onThread:[NSThread mainThread]
                   withObject:nil
                waitUntilDone:NO];
    }else if (context == kDurationKVOKey) {
        [self performSelector:@selector(_timerAction:)
                     onThread:[NSThread mainThread]
                   withObject:nil
                waitUntilDone:NO];
    }else if (context == kBufferingRatioKVOKey) {
        //        [self performSelector:@selector(_updateBufferingStatus)
        //                     onThread:[NSThread mainThread]
        //                   withObject:nil
        //                waitUntilDone:NO];
    }else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)_updateStatus{
    switch ([_streamer status]) {
        case DOUAudioStreamerPlaying:
            [_audioPalyerView.playBtn setImage:[UIImage imageNamed:@"暂停键"] forState:UIControlStateNormal];
            break;
        case DOUAudioStreamerPaused:
            [_audioPalyerView.playBtn setImage:[UIImage imageNamed:@"播放键"] forState:UIControlStateNormal];
            break;
        case DOUAudioStreamerIdle:
            break;
        case DOUAudioStreamerFinished:
//            [self nextButtonAction];
            break;
        case DOUAudioStreamerBuffering:
            
            break;
        case DOUAudioStreamerError:
            
            break;
    }
}
 */
/*
#pragma mark ------  播放按钮
- (void)playButtonAction:(UIButton*)button{
    button.selected = !button.selected;
    if (button.selected) {
//        if (self.streamer){
            [self.streamer play];
//            开启
            [self.timer setFireDate:[NSDate distantPast]];
//        }else{
//            [self createPlayer];
//            [self.streamer play];
//        }
        [_audioPalyerView.playBtn setImage:[UIImage imageNamed:@"暂停键"] forState:UIControlStateNormal];
        
    }else {
        [_streamer pause];
        [_audioPalyerView.playBtn setImage:[UIImage imageNamed:@"播放键"] forState:UIControlStateNormal];
//        关闭
        [self.timer setFireDate:[NSDate distantFuture]];
    }
}

- (void)_actionSliderProgress:(id)sender{
    self.sliding = YES;
}
- (void)reloadprogressValue{
    self.sliding = NO;
}
- (void)durationSliderTouchEnded:(UISlider *)slider{
    [self performSelector:@selector(reloadprogressValue) withObject:self afterDelay:0.5];
    [_streamer setCurrentTime:[_streamer duration] * [slider value]];
    
}

- (void)lastButtonAction{
    --num;
    [_streamer pause];
    self.track.audioFileURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",_mutableSongURLArr[num]]];
    
    // 上一曲 下一曲没有做实现  原理就是重新创建播放器，，添加新的网址播放
    /// 我这里直接[self loadData] 就可以了
    
}


- (void)nextButtonAction{
    
    ++num;
    if (num == _mutableSongURLArr.count) {
        num = 0;
    }
    
    _track.audioFileURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",_mutableSongURLArr[num]]];
    _streamer = [DOUAudioStreamer streamerWithAudioFile:_track];
    
    [_streamer play];
    // 开启
    [self.timer setFireDate:[NSDate distantPast]];
//    [self _cancelStreamer];
    
     
}
*/
-(void)enterCurrentUser
{
    WeakSelf
    if ([_hrSquareAudioPlayerModel.UserLocalId isEqualToString:USERID]) return ;
    HRDynamicViewController *dynamicVC = [HRDynamicViewController new];
    dynamicVC.currentUserID = _hrSquareAudioPlayerModel.UserLocalId;
    //            dynamicVC.hidesBottomBarWhenPushed = YES;
    
    [weakSelf.navigationController pushViewController:dynamicVC animated:YES];
}
/*
- (void)_timerAction:(id)timer{
    if ([_streamer duration] == 0.0) {
        [_audioPalyerView.slider setValue:0.0f animated:NO];
    }else {
        // 播放进度条
        if (self.sliding == YES) {
            
        }else{
            [_audioPalyerView.slider setValue:[_streamer currentTime] / [_streamer duration] animated:YES];
//            NSInteger cuTiem = [_streamer currentTime];
//            NSInteger durationTime = _hrSquareAudioPlayerModel.SoundLength
//            [_audioPalyerView.slider setValue:[_streamer currentTime] / [_streamer bufferingRatio] animated:YES];
        }
        
        // 当前播放时间
        double minutesElapsed = floor(fmod([_streamer currentTime]/ 60.0,60.0));
        double secondsElapsed = floor(fmod([_streamer currentTime],60.0));
        // 音频总时长
        double minutesElapsedtotal = floor(fmod([_streamer duration]/ 60.0,60.0));
        double secondsElapsedtotal = floor(fmod([_streamer duration],60.0));
        
    }
    // 缓存进度
//    _audioPalyerView.progress.progress = [_streamer bufferingRatio];
}

- (void)_cancelStreamer{
    if (_streamer != nil) {
        [_streamer pause];
        [_streamer removeObserver:self forKeyPath:@"status"];
        [_streamer removeObserver:self forKeyPath:@"duration"];
        [_streamer removeObserver:self forKeyPath:@"bufferingRatio"];
        _streamer = nil;
    }
}

- (void)backaction{
    [_timer invalidate];
    _timer = nil;
    [self _cancelStreamer];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
#pragma mark 解决slider 小范围滑动不能触发的问题
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    if([gestureRecognizer locationInView:gestureRecognizer.view].y >= _audioPalyerView.slider.frame.origin.y && !_audioPalyerView.slider.hidden)
        return NO;
    return YES;
}

- (void)addCurrentTimer
{
    if (![_streamer status] == DOUAudioStreamerPlaying) return;
    
    //在新增定时器之前，先移除之前的定时器
    [self removeCurrentTimer];
    
//    [self updateCurrentTimer];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCurrentTimer) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)removeCurrentTimer
{
    [self.timer invalidate];
    self.timer = nil;
}
*/

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    if ([[NSUserDefaults standardUserDefaults] integerForKey:@"num"]) {
        num = [[NSUserDefaults standardUserDefaults] integerForKey:@"num"];
        DDLog(@"num ================ %d",num);
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
